<?php

require_once 'dbutils.php';
require_once 'RestUtils.php';
require_once 'Base.php';

class UserJourneysStatus extends Base
{

    function GET($matches)
    {
        $req = RestUtils::processRequest('GET');
        $req_vars = $req->getRequestVars();
        $db_vars = dbutils::translate_rest_params($req_vars);
        $res = $this->selectUserJourneysStatus($db_vars);
        if ($res['code'] == 0)
            RestUtils::sendResponse(200, $res['result'], 'application/json');
        else
            RestUtils::sendResponse(404, dbutils::error_to_json($res['code'], $res['message']), 'application/json');
    }

    function PUT($matches)
    {
        $req = RestUtils::processRequest('POST');
        $req_vars = $req->getRequestVars();
        $db_vars = dbutils::translate_rest_params($req_vars);
        $res = $this->updateUserJourneysStatus($db_vars);
        if ($res['code'] == 0)
            RestUtils::sendResponse(200);
        else
            RestUtils::sendResponse(404, dbutils::error_to_json($res['code'], $res['message']), 'application/json');
    }

    private function selectUserJourneysStatus($values)
    {
        $code = 0;
        $msg = '';
        $result = null;
        try {
            if (!$values)
                return array('code' => -1, 'message' => 'required request parameters not found', 'result' => null);

            if (!array_key_exists('id_user', $values))
                return array('code' => -1, 'message' => 'required request parameters not found', 'result' => null);

            $query = "SELECT j.id AS id_journey,
                             j.status AS journey_status
                      FROM journeys j, user_journeys uj
                      WHERE uj.id_journey = j.id
                      AND uj.id_user = {$values['id_user']}";

            if (array_key_exists('fl_owner', $values))
                $query .= " AND uj.fl_owner = '{$values['fl_owner']}'";

            $db_handle = @pg_pconnect(dbutils::$conn_string);
            $result = @pg_query($db_handle, $query);
            if ($result)
                $result = dbutils::dbresult_to_json($result);
            else {
                $code = -1;
                $msg = 'no db records found ' . @pg_last_error($db_handle);
            }
            @pg_close($db_handle);

        } catch (Exception $e) {
            $code = $e->getCode();
            $msg = $e->getMessage();
        }

        return array('code' => $code, 'message' => $msg, 'result' => $result);
    }

    private function updateUserJourneysStatus($values)
    {
        $code = 0;
        $msg = '';
        $result = null;
        try {
            if (!$values)
                return array('code' => -1, 'message' => 'required request parameters not found', 'result' => null);

            if (!array_key_exists('id_journey', $values) ||
                !array_key_exists('id_user', $values) ||
                !array_key_exists('journey_status', $values))
                return array('code' => -1, 'message' => 'required request parameters not found', 'result' => null);

            $query = "SELECT *
                        FROM user_journeys
                        WHERE id_user = {$values['id_user']}
                        AND id_journey = {$values['id_journey']}
                        AND fl_owner = '1'";

            $db_handle = @pg_pconnect(dbutils::$conn_string);

            $result = @pg_query($db_handle, $query);

            if ($result && @pg_num_rows($result) == 1) {
                $query = "SELECT id_user
                            FROM user_journeys
                            WHERE id_journey = {$values['id_journey']}
                            AND fl_owner = '0'";

                $result = @pg_query($db_handle, $query);

                if ($result && @pg_num_rows($result) > 0) {

                    $query = "UPDATE journeys
                                SET status = {$values['journey_status']}
                              WHERE id = {$values['id_journey']};";

                    for ($row = 0; $row < @pg_num_rows($result); $row++) {
                        $res = @pg_fetch_array($result, $row, PGSQL_NUM);
                        $id_recipient = $res[0];

                        $query .= "INSERT INTO messages (title, body,
                                            datetime, id_journey, id_sender,
                                            id_recipient)
                                    VALUES ('JOURNEY STATUS CHANGED',
                                            'JOURNEY IS {$values['journey_status']} TO SUBSCRIPTION',
                                            LOCALTIMESTAMP(0),
                                            {$values['id_journey']},
                                            {$values['id_user']}, {$id_recipient});";
                    }
                    $result = @pg_query($db_handle, $query);

                    if (!$result) {
                        $code = -1;
                        $msg = 'updating records not possible ' . @pg_last_error($db_handle);
                    }
                } else {
                    $code = -2;
                    $msg = 'no users to notify ' . @pg_last_error($db_handle);
                }
            } else {
                $code = -2;
                $msg = 'no db records found or not journey owner ' . @pg_last_error($db_handle);
            }
            @pg_close($db_handle);

        } catch (Exception $e) {
            $code = $e->getCode();
            $msg = $e->getMessage();
        }

        return array('code' => $code, 'message' => $msg, 'result' => $result);
    }
}

?>